/*
 * Copyright 2007-2008 Brian Cavalier
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package  org.bc.iterate;

import java.util.regex.Pattern;
	
/**
 * Sed is a {@link org.bc.iterate.Transform} that applies regular expression matching and
 * substitutions.  Sed operates on {@code String}s only.
 * 
 * @author Brian Cavalier
 * @see Transform
 */
public class Sed implements Transform<CharSequence>{
	private Pattern _pattern;
	private String _replace;
	
	
	/**
	 * Constructs a Sed that will replace text matching the supplied pattern
	 * with the supplied replacement.  Capture references are allowed in the
	 * replacement string.
	 *
	 * @param p Pattern to match
	 * @param replace String to replace matches with.  Capture references
	 * are allowed.
	 */
	public Sed(Pattern p, String replace) {
		_pattern = p;
		_replace = replace;
	}
	
	/**
	 * Replaces matches found in the supplied String.
	 *
	 * @param item String to match and replace
	 * @return String with all matches replaced
	 */
	public String apply(CharSequence item) {
		return _pattern.matcher(item).replaceAll(_replace);
	}
}